package com.woniu.logger;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;

import com.woniu.logger.conf.LoggerConfig;
import com.woniu.logger.conf.LoggerLevelEnum;
import com.woniu.logger.sql.DdlSqlFactory;
import com.woniu.logger.sql.IDdlSql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



/**
 * 功能描述: 日志备份任务 <br/>
 */
@Component
public class LoggerInfoBackTask {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private LoggerConfig loggerConfig;

    private IDdlSql ddl;

    /**
     * 功能描述: 每天0点1秒开始执行备份表（确定日期） <br/>
     */
    @Scheduled(cron = "1 0 0 * * ?")
    public void backTask() throws Throwable {
        if (LoggerLevelEnum.NONE.equals(loggerConfig.getLevel())) {
            return;
        }
        Connection conn = dataSource.getConnection();
        try (Statement statement = conn.createStatement()) {
            DbType dbType = JdbcUtils.getDbType(conn.getMetaData().getURL());
            ddl = DdlSqlFactory.valueOf(dbType.name()).getDdl();
            String yesterday = DateUtil.format(DateUtil.yesterday(), DatePattern.PURE_DATE_FORMAT);
            // 查询表有没有存在
            if (!existTable(statement, yesterday)) {
                backTable(statement, yesterday);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述: 每日备份操作 <br/>
     */
    public void backTable(Statement statement, String yesterday) throws SQLException {
        // 先备份
        statement.execute(ddl.backTable(yesterday));
        // 再创建表
        statement.execute(ddl.createTable());
    }

    /**
     * 功能描述: 是否存在表 <br/>
     */
    private boolean existTable(Statement statement, String yesterday) throws SQLException {
        ResultSet resultSet = statement.executeQuery(ddl.queryTable(yesterday));
        resultSet.next();
        return resultSet.getInt(1) == 1;
    }

}
